package com.itmake.sample.toolbox.python;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;

/**
 * Python 工具
 *
 * @author Amjacks
 * @since 2023/08/10
 */
public class PyUtil {

    /**
     * 操作 python
     * @param pyName resource 下 /aa/aaa.py
     * @param parameter 参数
     */
    public String operationPy(String pyName, String[] parameter) {
        Process proc = null;
        StringBuilder sb = new StringBuilder();
        try {
            String[] args = new String[parameter.length + 2];
            // 字符集
            String charset = "utf-8";
            // 系统类型
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("windows")) {
                args[0] = "python";
                charset = "gbk";
            } else if (os.contains("linux")) {
                args[0] = "python3";
            }
            // 文件路径
            args[1] = Objects.requireNonNull(this.getClass().getResource(pyName)).getPath().substring(1);
            // 组拼命令
            System.arraycopy(parameter, 0, args, 2, parameter.length);
            // 执行py文件
            proc = Runtime.getRuntime().exec(args);
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), charset));
            // 结果
            String line = null;
            while ((line = in.readLine()) != null) {
                sb.append(line).append("\r\n");
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return sb.toString();
    }
}
